<template>
    <j-modal :title="`问诊 ${record.name}`" :width="800" :visible="visible" fullscreen @ok="handleOk" :closable="false"
        @cancel="handleCancel" okText="保存问诊记录" cancelText="结束问诊" :cancelButtonProps="{ class: 'consultationCancel' }">
        <a-card :bordered="false">
            <div class="mainV">
                <a-spin tip="通讯连接中..." :spinning="connectionStateLoad">
                    <div class="metV">
                        <div class="metVi" id="remotetracks"></div>
                    </div>
                </a-spin>
                <div class="contV">
                    <div class="tV">患者信息</div>
                    <div class="pV">
                        <div class="pVl">
                            <img :src="getFileAccessHttpUrl(patientInfo.image)" alt="" />
                        </div>
                        <div class="pVr">
                            <div class="pVri"><span>姓名：</span>{{ patientInfo.name }}</div>
                            <div class="pVri"><span>性别：</span>{{ patientInfo.sex }}</div>
                            <div class="pVri"><span>出生日期：</span>{{ patientInfo.birth }}</div>
                            <div class="pVri"><span>地址：</span>{{ patientInfo.address }}</div>
                            <div class="pVri"><span>身份证号：</span>{{ patientInfo.idCard }}</div>
                            <div class="pVri"><span>联系电话：</span>{{ patientInfo.phone }}</div>
                            <div class="pVri"><span>血型：</span>{{ patientInfo.bloodType }}</div>
                            <div class="pVri"><span>过敏史：</span>{{ patientInfo.allergy }}</div>
                            <div class="pVri"><span>邮箱地址：</span>{{ patientInfo.mail }}</div>
                            <div class="pVri"><span>医保卡号：</span>{{ patientInfo.medicareCard }}</div>
                        </div>
                    </div>
                    <a-divider dashed />
                    <div class="tV">问诊资料 (共 {{ fileList.length }} 项)</div>
                    <div class="fVs">
                        <div class="fV">
                            <div class="fVi" v-for="(i, o) in fileList" :key="o" @click="downLoadFile(i)">{{
                                i.split('preview/')[1] }}</div>
                        </div>
                        <div class="fVb">
                            <j-upload1 buttonSize="small" v-model="fileList1" text="共享文件"></j-upload1>
                            <a-button size="small" icon="redo" @click="getFileListData" type="primary">刷新</a-button>
                        </div>
                    </div>
                    <a-divider dashed />
                    <div class="lastV">
                        <div class="lastVl">
                            <div class="tV">参诊人员</div>
                            <div class="userV">
                                <div class="userVi" v-for="(i, o) in record.wzOnlineInquiryUser" :key="o">
                                    <img class="userViImg" :src="getFileAccessHttpUrl(i.image)" alt="" />
                                    <div class="userVic">
                                        <div>{{ i.name }} ( {{ i.dept_dictText }} )</div>
                                        <div class="userVico">{{ i.orgId_dictText }}</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="lastVr">
                            <div class="tV">问诊报告</div>
                            <div class="formV">
                                <a-form-model ref="form" :model="model" :rules="rules" slot="detail">
                                    <a-row>
                                        <a-col :span="24">
                                            <a-form-model-item label="疾病名称分类" required prop="illnessClass"
                                                :labelCol="labelCol" :wrapperCol="wrapperCol">
                                                <a-input v-model="model.illnessClass" placeholder="请输入疾病名称分类"></a-input>
                                            </a-form-model-item>
                                        </a-col>
                                        <a-col :span="24">
                                            <a-form-model-item label="治疗描述" required prop="healDesc"
                                                :labelCol="labelCol" :wrapperCol="wrapperCol">
                                                <a-textarea v-model="model.healDesc" rows="4" placeholder="请输入治疗描述" />
                                            </a-form-model-item>
                                        </a-col>
                                        <a-col :span="24">
                                            <a-form-model-item label="诊断结果" required prop="diagnosis"
                                                :labelCol="labelCol" :wrapperCol="wrapperCol">
                                                <a-textarea v-model="model.diagnosis" rows="4" placeholder="请输入诊断结果" />
                                            </a-form-model-item>
                                        </a-col>
                                        <a-col :span="24">
                                            <a-form-model-item label="处方信息" required prop="prescription"
                                                :labelCol="labelCol" :wrapperCol="wrapperCol">
                                                <a-input v-model="model.prescription" placeholder="请输入处方信息"></a-input>
                                            </a-form-model-item>
                                        </a-col>
                                        <a-col :span="24">
                                            <a-form-model-item label="是否需要复诊" required prop="isVisit"
                                                :labelCol="labelCol" :wrapperCol="wrapperCol">
                                                <j-dict-select-tag v-model="model.isVisit" placeholder="请选择是否需要复诊"
                                                    dictCode="SFXYFZ" style="width: 100%" />
                                            </a-form-model-item>
                                        </a-col>
                                        <a-col :span="24">
                                            <a-form-model-item label="复诊时间" :required="model.isVisit" prop="visitDate"
                                                v-if="model.isVisit == 1" :labelCol="labelCol" :wrapperCol="wrapperCol">
                                                <j-date placeholder="请选择复诊时间" dateFormat="YYYY-MM-DD HH:mm:ss"
                                                    :showTime="true" v-model="model.visitDate" style="width: 100%" />
                                            </a-form-model-item>
                                        </a-col>
                                        <a-col :span="24">
                                            <a-form-model-item label="备注" prop="remark" :labelCol="labelCol"
                                                :wrapperCol="wrapperCol">
                                                <a-textarea v-model="model.remark" rows="4" placeholder="请输入备注" />
                                            </a-form-model-item>
                                        </a-col>
                                    </a-row>
                                </a-form-model>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </a-card>
    </j-modal>
</template>

<script>
import { getAction, postAction, getFileAccessHttpUrl } from '@/api/manage';
import QNRTC from "qnweb-rtc";
import JUpload1 from '@/components/jeecg/JUpload1'
import moment from 'moment'
const client = QNRTC.createClient();

export default {
    components: {
        JUpload1
    },
    data() {
        return {
            moment,
            connectionStateLoad: false,
            getFileAccessHttpUrl,
            labelCol: {
                xs: { span: 24 },
                sm: { span: 5 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 },
            },
            visible: false,
            record: {},
            model: {
                illnessClass: '',
                healDesc: '',
                diagnosis: '',
                prescription: '',
                isVisit: null,
                visitDate: '',
                remark: '',
            },
            rules: {
                illnessClass: [{ required: true, message: '请输入疾病名称分类' }],
                healDesc: [{ required: true, message: '请输入治疗描述' }],
                diagnosis: [{ required: true, message: '请输入诊断结果' }],
                prescription: [{ required: true, message: '请输入处方信息' }],
                isVisit: [{ required: true, message: '请选择是否需要复诊' }],
                visitDate: [{ required: true, message: '请选择复诊时间' }],
            },
            patientInfo: {},
            fileList: [],
            fileList1: [],
        }
    },
    watch: {
        fileList1: {
            handler(val) {
                if (val.length && val.length > 0) {
                    this.upLoadFile(val)
                }
            },
            deep: true
        }
    },
    mounted() {
    },
    methods: {
        show(record) {
            this.record = record;
            this.visible = true;
            console.log('record', record)
            getAction('/wz/patient/wzPatientInfo/queryById', { id: record.wzReserve.patientId }).then(res => {
                this.patientInfo = res.result;
            })
            this.getFileListData()
            getAction('/wz/rtc/wzRtc/getRoomToken', {
                roomName: record.name,
            }).then(res => {
                this.joinRoom(res);
            })
        },
        handleCancel() {
            const that = this;
            that.$confirm({
                title: '确认结束当前问诊？请确保已保存问诊记录！',
                async onOk() {
                    await client.leave();
                    that.visible = false
                },
                onCancel() { },
            });
        },
        handleOk() {
            const that = this;
            this.$refs.form.validate(valid => {
                if (valid) {
                    this.model = {
                        ...this.model,
                        roomId: this.record.id,
                        patientId: this.record.wzReserve.patientId,
                        doctorId: this.record.wzReserve.doctorId,
                        orgId: this.record.orgId,
                        deptId: this.record.deptId,
                        healTime: moment().format('YYYY-MM-DD HH:mm:ss'),
                    }
                    postAction('/wz/heal/wzHealRecord/add', this.model).then(res => {
                        if (res.success) {
                            that.$message.success(res.message)
                        } else {
                            that.$message.error(res.message)
                        }
                    })
                }
            })
        },
        downLoadFile(url) {
            window.open(getFileAccessHttpUrl(url));
        },
        async joinRoom(res) {
            const that = this
            that.connectionStateLoad = true
            // 创建QNRTCClient对象
            // 需要先监听对应事件再加入房间
            client.on("user-published", this.handleUserPublished);
            if (QNRTC.isBrowserSupported) {
                console.warn("support!");
            } else {
                console.warn("not support!");
            }
            // 测试摄像头采集
            try {
                const track = await QNRTC.createCameraVideoTrack();
            } catch (e) {
                console.warn("camera track not support!");
            }

            // 测试麦克风采集
            try {
                const track = await QNRTC.createMicrophoneAudioTrack();
            } catch (e) {
                console.warn("microphone track not support!");
            }
            const result = await QNRTC.checkSystemRequirements();
            if (result.ok) {
                console.warn("test ok!");
            } else {
                console.warn("test fail", result.reason);
            }

            client.on("user-unpublished", this.handleUserUnPublished);
            client.on("connection-state-changed", async function (connectionState, info) {
                console.warn('房间连接状态变化', connectionState, info)
                if (connectionState == 'CONNECTED') {
                    const localTracks = await QNRTC.createMicrophoneAndCameraTracks();//这个localTracks  是不是音视频一块推上去了
                    for (const track of localTracks) {
                        if (track.isVideo()) {
                            that.playUserTracks([track]);
                        }
                    }
                    await client.publish(localTracks);
                }
                if (connectionState == 'CONNECTED' || connectionState == 'RECONNECTED') {
                    that.connectionStateLoad = false
                }
            })
            await client.join(res)
        },
        async handleUserPublished(userID, tracks) {
            try {
                const { videoTracks, audioTracks } = await client.subscribe(tracks);
                console.log('videoTracks', videoTracks)
                this.playUserTracks([...videoTracks, ...audioTracks]);
            } catch (e) {
                alert(e.message, "warning");
            }
        },
        playUserTracks(tracks) {
            console.warn('tracks', tracks)
            tracks.map((track, index) => {
                if (track.isAudio()) {
                    track.play(document.body)
                } else {
                    const div = document.createElement("div");
                    if (track.trackID) div.id = track.trackID;
                    const remotetracks = document.getElementById("remotetracks");
                    div.classList.add('remotetracksItems')
                    const img = document.createElement("img");
                    img.setAttribute('src', require('../../../../assets/f2.png'))
                    img.classList.add('remotetracksItemimg')
                    img.onclick = function () {
                        if (img.classList.contains('remotetracksItem1')) {
                            img.setAttribute('src', require('../../../../assets/f2.png'))
                            img.closest('.remotetracksItems').classList.remove('remotetracksItem')
                            img.classList.remove('remotetracksItem1')
                        } else {
                            img.setAttribute('src', require('../../../../assets/f1.png'))
                            img.classList.add('remotetracksItem1')
                            img.closest('.remotetracksItems').classList.add('remotetracksItem')
                        }
                    }
                    div.appendChild(img);
                    remotetracks.appendChild(div);
                    track.play(div)
                }
            })
        },
        handleUserUnPublished(userID, tracks) {
            for (const track of tracks) {
                let div = document.getElementById(track.trackID);
                if (div) div.remove();
            }
        },
        upLoadFile(fileList) {
            getAction('/wz/online/wzOnlineInquiry/shareFile', { id: this.record.id, shareFile: fileList }).then(res => {
                this.fileList1 = []
                if (res.success) {
                    this.getFileListData()
                    this.$message.success(res.message)
                } else {
                    this.$message.error(res.message)
                }
            })
        },
        getFileListData() {
            getAction('/wz/online/wzOnlineInquiry/getShareFile', { id: this.record.id }).then(res => {
                if (res.result && res.result.length > 0) {
                    this.fileList = res.result.split(',')
                } else {
                    this.fileList = []
                }
            })
        }
    },
    async beforeDestroy() {
        await client.leave();
    }
}
</script>

<style lang="less" scoped>
.mainV {
    display: flex;

    .contV {
        margin-left: 20px;
        width: calc(100% - 860px);

        .pV {
            display: flex;
            align-items: center;
            margin-bottom: 20px;

            .pVl {
                box-shadow: 0 0 12px #ccc;
                border-radius: 50%;
                overflow: hidden;
                width: 50px;
                height: 50px;
                margin-right: 20px;

                img {
                    width: 50px;
                    height: 50px;
                }
            }

            .pVr {
                width: calc(100% - 70px);
                display: flex;
                align-items: center;
                flex-wrap: wrap;

                .pVri {
                    display: flex;
                    align-items: center;
                    margin-bottom: 20px;
                    width: 25%;
                    margin-bottom: 3px;
                    color: #000;

                    span {
                        color: #777;
                    }
                }
            }
        }

        .fVs {
            position: relative;

            .fV {
                position: relative;
                display: flex;
                flex-wrap: nowrap;
                overflow-x: auto;

                .fVi {
                    color: #008dff;
                    margin-right: 30px;

                    &:hover {
                        cursor: pointer;
                        text-decoration: underline;
                    }
                }
            }

            .fVb {
                position: absolute;
                top: -30px;
                right: 0px;
                display: flex;
                z-index: 99;
                align-items: center;
                width: 200px;
                justify-content: space-around;
            }
        }


        .formV {
            height: 360px;
            max-height: 360px;
            overflow-y: auto;
            margin-top: 10px;
        }
    }
}

.lastV {
    display: flex;

    .lastVl {
        width: 200px;
        margin-right: 15px;
        height: 100%;

        .userV {
            height: 360px;
            max-height: 360px;
            overflow-y: auto;
            margin-top: 10px;

            .userVi {
                display: flex;
                align-items: center;
                margin-bottom: 5px;
                padding-bottom: 5px;
                border-bottom: 1px dashed #eee;

                .userViImg {
                    width: 40px;
                    height: 40px;
                    border-radius: 50%;
                    box-shadow: 0 0 4px;
                    margin-right: 10px;
                    margin-left: 3px;
                }

                .userVic {
                    display: flex;
                    flex-direction: column;
                    justify-content: space-around;

                    .userVico {
                        width: 135px;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        display: -webkit-box;
                        -webkit-line-clamp: 2;
                        -webkit-box-orient: vertical;
                    }
                }
            }
        }
    }

    .lastVr {
        padding-left: 15px;
        border-left: 1px dashed #eee;
        width: calc(100% - 230px);
    }
}

.tV {
    display: flex;
    align-items: center;
    margin-bottom: 5px;
    font-weight: bold;

    &::before {
        content: '';
        width: 4px;
        height: 22px;
        background-color: #00B494;
        border-radius: 4px;
        margin-right: 10px;
    }
}

.metV {
    display: flex;
    background: #000;
    padding: 10px 0 0 0;
    border-radius: 6px;
    width: 840px;
    height: 700px;
    max-height: 700px;
    overflow-y: auto;

    .metVi {
        display: flex;
        flex-wrap: wrap;
        margin: 10px;
        height: 180px !important;

        :deep .remotetracksItems {
            width: 260px !important;
            height: 180px !important;
            position: relative;
            border: 1px solid #ccc;
            border-radius: 8px;
            padding: 5px;
            margin: 5px;
        }

        :deep .remotetracksItemimg {
            position: absolute;
            display: block;
            z-index: 99;
            right: 10px;
            bottom: 10px;
            width: 22px;
            height: 22px;
        }

        :deep .remotetracksItem {
            width: 500px !important;
            height: 300px !important;
        }
    }
}

:deep.ant-divider-horizontal {
    margin: 12px 0 !important;
}

:deep .consultationCancel {
    background-color: #ff4d4f !important;
    border-color: #ff4d4f !important;
    color: #fff !important;

    &:hover {
        background-color: #ff7875 !important;
        border-color: #ff7875 !important;
    }
}
</style>